package com.lions.client.model;

import com.google.gwt.storage.client.Storage;
import com.lions.client.view.popup.MyPopupPanel;

public class HTMLStorage {
	
	public HTMLStorage(ModuleList modList) {
		list = modList;
		if (!Storage.isLocalStorageSupported())
			new MyPopupPanel("HTML Storage Not Available", "Error: HTML Storage Not Available", "errorpopupwrapper");
	}
	/**
	 * Loads data from the session storage.
	 * This only loads modules at this time.
	 */
	public void storageLoad() {
		listStore = Storage.getLocalStorageIfSupported();
		if (listStore != null) {
			for (int i=0; i < listStore.getLength(); i++) {
				if (listStore.key(i).equals("Module"+i)) {
					list.add(new Module(listStore.getItem(listStore.key(i).toString()).toString()));
				}
			}
		}
		listStore = null;
	}
	
	/**
	 * Adds a module to the local session storage,
	 * only accepts modules at this time.
	 * @param mod A module to add
	 */
	public void storageSave(Module mod) {
		listStore = Storage.getLocalStorageIfSupported();
		if (listStore != null) {
			listStore.setItem("Module"+listStore.getLength(), mod.toString());
			//System.out.println("Storage Save");
		}
		listStore = null;
	}
	
	/**
	 * Clears all of the data within the local storage.
	 */
	public void storageClear() {
		listStore = Storage.getLocalStorageIfSupported();
		listStore.clear();
		list.clear();
		listStore = null;
	}

	public void removeModule(Module mod) {
		listStore = Storage.getLocalStorageIfSupported();
		if (listStore != null) {
			for (int i=0; i < listStore.getLength(); i++) {
				if (listStore.key(i).equals("Module"+i)) {
					if (mod.equals(new Module(listStore.getItem(listStore.key(i).toString()).toString()))) {
						listStore.removeItem("Module"+i);
						//System.out.println("Removed");
					}
				}
			}
		}
	}
	
	private ModuleList list;
	private Storage listStore = null;
}
